﻿using AntMovement.Core;
using AntMovement.Core.Attributes;
using AntMovement.Core.Entity;
using AntMovement.Core.Hardware;
using AntMovement.Core.IParameter;
using AntMovement.Core.Logic;
using AntMovement.Core.Logic.Base;
using AntMovement.Core.Model;
using AntMovement.Parameter;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.Handle.TPTest
{
    [FlowAttributes(nameof(ModuleMotion), 4)]
    public class ModuleMotion : TaskBase
    {
        #region 轴变量
        private AxisMotion _axisX = default, _axisY = default, _axisZ = default, _axisR = default;

        private Axis _axisEntityY;
        private Axis _axisEntityR;
        private Axis _axisEntityX;
        #endregion

        #region 上升沿
        private bool _oneKeyHome = false;
        #endregion

        #region 定时器
        private Ton _tonHome = new Ton();
        private Ton _ton1 = new Ton();
        private Ton _ton2 = new Ton();
        
        #endregion

        #region 点位
        private PointPositionInfoModel _拍照位;
        private PointPositionInfoModel _取料位;
        private PointPositionInfoModel _检测位;
        private PointPositionInfoModel _良品位;
        private PointPositionInfoModel _不良品位;
        private PointPositionInfoModel _标定点位;
        #endregion

        #region 输入点
        private NormalClose _缓存位真空信号;
        private NormalOpen _Z轴吸嘴真空信号;
        #endregion

        #region 输出点
        private ICoil _缓存位真空;
        private ICoil _Z轴吸嘴真空;
        private ICoil _Z轴吸嘴吹气;
        #endregion

        #region 报警变量
        #endregion

        #region 私有变量
        private string _pointname = default;
        private Stopwatch _stopwatch = new Stopwatch();
        private int _count = 0;
        private bool _debug = true;
        #endregion
        public ModuleMotion(ITemporaryParameter temporary, IIOParameter iop, IAxisParameter axisp, IDialogHost dialogHost, ILog log)
            : base(temporary, iop, axisp, dialogHost, log)
        {
            _axisX = axisp.GetAxisMotion("X轴");
            _axisY = axisp.GetAxisMotion("Y轴");
            _axisZ = axisp.GetAxisMotion("Z轴");
            _axisR = axisp.GetAxisMotion("R轴");

            _axisEntityX = axisp.GetAxisEntity("X轴");
            _axisEntityY = axisp.GetAxisEntity("Y轴");
            _axisEntityR = axisp.GetAxisEntity("R轴");

            _缓存位真空信号 = iop.GetNormalClose("缓存位真空信号");
            _Z轴吸嘴真空信号 = iop.GetNormalOpen("Z轴吸嘴真空信号");


            _缓存位真空 = iop.GetCoil("缓存位真空");
            _Z轴吸嘴真空 = iop.GetCoil("Z轴吸嘴真空");
            _Z轴吸嘴吹气 = iop.GetCoil("Z轴吸嘴吹气");

            _拍照位 = axisp.GetPointPosition("拍照位");
            _取料位 = axisp.GetPointPosition("取料位");
            _检测位 = axisp.GetPointPosition("检测位");
            _良品位 = axisp.GetPointPosition("良品位");
            _不良品位 = axisp.GetPointPosition("不良品位");
            _标定点位 = axisp.GetPointPosition("标定点位");
        }

        public override void EmergencyStop()
        {

        }

        public override void Handle()
        {
            if (SignalOn(0))
            {
                if (PointPositionMove(_拍照位))
                {
                    _temporary.Status_缓存工位.SafetyPosition = !_debug;
                    NextStep();
                }
            }
            if (SignalOn(10))
            {
                if (_temporary.Status_缓存工位.Permit_TakeMaterials || _debug)
                {
                    _temporary.Status_缓存工位.SafetyPosition = false;
                    if (PointPositionMove(_取料位))
                    {
                        if (_count > 0)
                        {
                            _stopwatch.Stop();
                            _log.Info($"第[{_count}]片料往返耗时：{_stopwatch.Elapsed.TotalMilliseconds} ms");
                            _stopwatch.Restart();
                        }
                        _stopwatch.Start();
                        NextStep();
                    }
                }
            }
            if (SignalOn(20))
            {
                _axisZ.Move(_取料位.ZPulse, 20000);
                if (_axisZ.ArrivalLocation)
                {
                    NextStep();
                }
            }
            if (SignalOn(30))
            {
                _缓存位真空.Execute(false);
                if (_缓存位真空信号.Execute() || _debug)
                {
                    _Z轴吸嘴真空.Execute(true);
                    NextStep();
                }
            }
            if (SignalOn(40))
            {
                if (_Z轴吸嘴真空信号.Execute() || _debug)
                {
                    NextStep();
                }
                //检测吸嘴真空超时时间

            }
            if (SignalOn(50))
            {
                _axisZ.Move(0, 20000);//13000
                if (_axisZ.ArrivalLocation)
                {
                    _temporary.Status_缓存工位.Permit_TakeMaterials = false;
                    NextStep();
                }
            }
            if (SignalOn(60))
            {
                if (_Z轴吸嘴真空信号.Execute() || _debug)
                {
                    if (PointPositionMove(_拍照位))
                    {
                        _temporary.Status_缓存工位.SafetyPosition = true;
                        _temporary.Status_缓存工位.WithdrawalComplete = true;
                        NextStep();
                    }
                }
                else
                {
                    //吸嘴报警
                }
            }
            if (SignalOn(70))
            {
                _ton1.Time(200, true);
                if (_ton1.Out)
                {
                    _ton1.Time(200, false);
                    NextStep(60);
                }
            }
            /*这里是视觉交互逻辑*/
            if (SignalOn(130))
            {
                if (PointPositionMove(_检测位))
                {
                    NextStep();
                }
            }
            if (SignalOn(140))
            {
                _axisZ.Move(_检测位.ZPulse, 20000);
                if (_axisZ.ArrivalLocation)
                {
                    NextStep();
                }
            }
            if (SignalOn(150))
            {
                _ton1.Time(200, true);
                if (_ton1.Out)
                {
                    _ton1.Time(200, false);
                    NextStep();
                }
            }
            if (SignalOn(160))
            {
                _axisZ.Move(0, 20000);//13000
                if (_axisZ.ArrivalLocation)
                {
                    NextStep(100);
                }
            }
            /*
             中间是检测逻辑
             */
            if (SignalOn(260))
            {
                //去往OK还是NG
                if (!_temporary.OK && !_temporary.NG)
                {
                    if (PointPositionMove(_良品位))
                    {
                        _Z轴吸嘴真空.Execute(false);
                        _Z轴吸嘴吹气.Execute(true);
                        NextStep();
                    }
                }
            }
            //if (SignalOn(270))
            //{
            //    _axisZ.Move(_良品位.ZPulse, 20000);
            //    if (_axisZ.ArrivalLocation)
            //    {
            //        _Z轴吸嘴真空.Execute(false);
            //        _Z轴吸嘴吹气.Execute(true);
            //        NextStep();
            //    }
            //}
            if (SignalOn(270))
            {
                _ton2.Time(50, true);
                if (_ton2.Out)
                {
                    _ton2.Time(50, false);
                    _Z轴吸嘴吹气.Execute(false);
                    _temporary.OK = true;
                    _count++;
                    if (_temporary.Status_缓存工位.Permit_TakeMaterials)
                    {
                        _step = 10;
                    }
                    else
                    {
                        _step = 0;
                    }
                    //NextStep();
                }
            }
            //if (SignalOn(290))
            //{
            //    _axisZ.Move(9893, 20000);
            //    if (_axisZ.ArrivalLocation)
            //    {
            //        _temporary.OK = true;
            //        _count++;
            //        if (_temporary.Status_缓存工位.Permit_TakeMaterials)
            //        {
            //            _step = 10;
            //        }
            //        else
            //        {
            //            _step = 0;
            //        }
            //    }
            //}
            if (_temporary.SystemStatus.ManualOperation)
            {
                #region 点位移动
                if (_temporary.JogMove)
                {
                    if (_pointname != _temporary.JogName)
                    {
                        _pointname = _temporary.JogName;
                        _log.Info($"点位 [{_pointname}]");
                    }
                    var ponitData = ((Parameter.AxisParameter)_axisParameter).PointPosition.FirstOrDefault(x => x.Name == _temporary.JogName);
                    if (PointPositionMove(ponitData))
                    {
                        _log.Info($"点位 [{_pointname}] 运动完成");
                        _temporary.JogMove = false;
                    }
                }
                #endregion
                #region 一键回原
                if (_temporary.OneKeyHome)
                {
                    _tonHome.Time(1000, true);
                    _oneKeyHome = _tonHome.Out;
                }
                else
                {
                    _tonHome.Time(1000, false);
                }
                if (_oneKeyHome)
                {
                    if (!_axisZ.HomeComplete)
                    {
                        _axisZ.Home();
                    }
                    if (_axisZ.HomeComplete)
                    {
                        if (!_axisX.HomeComplete)
                            _axisX.Home();
                        if (!_axisY.HomeComplete)
                            _axisY.Home();
                        if (!_axisR.HomeComplete)
                            _axisR.Home();
                    }
                    if (_axisX.HomeComplete && _axisY.HomeComplete && _axisZ.HomeComplete && _axisR.HomeComplete)
                    {
                        _oneKeyHome = false;
                        _dialogHost.DialogShow("一键回原完成,允许开机！！！", Core.Enum.LogLevel.Success);
                    }
                }
                _temporary.HomeComplete = _axisX.HomeComplete && _axisY.HomeComplete && _axisZ.HomeComplete && _axisR.HomeComplete;
                #endregion
            }
        }

        public override void Resetting()
        {

        }

        public override void SafeStop()
        {

        }

        /// <summary>
        /// 不良品位的时候要进行避让
        /// </summary>
        /// <param name="point"></param>
        /// <param name="bl">默认(false)避让 true(不需要避让)</param>
        /// <returns></returns>
        private bool PointPositionMove(PointPositionInfoModel point, bool bl = false)
        {
            _axisZ.Move(0, 10000);
            if (!_axisZ.ArrivalLocation)
            {
                return false;
            }
            _axisR.Move(point.RPulse, 10000);
            if (point.Name == "不良品位")
            {
                _axisX.Move(point.XPulse, 10000);
                if (_axisEntityX.Status.CurrentPostion < 148000)
                {
                    return false;
                }
                _axisY.Move(point.YPulse, 10000);
            }
            else if (point.Name == "取料位" && !bl)
            {
                _axisY.Move(point.YPulse, 10000);
                if (_axisEntityY.Status.CurrentPostion < -1100)
                {
                    return false;
                }
                _axisX.Move(point.XPulse, 10000);
            }
            else
            {
                _axisX.Move(point.XPulse, 10000);
                _axisY.Move(point.YPulse, 10000);
            }
            return _axisX.ArrivalLocation && _axisY.ArrivalLocation && _axisR.ArrivalLocation;
        }
    }
}
